using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using Kaleida.ServiceMonitor.Framework;
using Kaleida.ServiceMonitor.Framework.Responses;

namespace Kaleida.ServiceMonitor.Operations.PreparedRequests
{
    public class HttpGet : PreparedRequest
    {
        private readonly string url;

        public HttpGet(string url)
        {
            this.url = url;
        }

        public override string Description
        {
            get { return string.Format("Fetch content from '{0}' using HTTP GET", url); }
        }

        public override object GetResponse()
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.UseDefaultCredentials = true;

            var stopwatch = Stopwatch.StartNew();
            var response = (HttpWebResponse)request.GetResponse();

            Stream stream = response.GetResponseStream();
            if (stream == null)
                throw new InvalidOperationException("Received null response from " + url);

            var reader = new StreamReader(stream);
            var content = reader.ReadToEnd();
            var timeTaken = stopwatch.Elapsed;
            return new HttpOperationResponse(content, timeTaken);

        }
    }
}